package net.lesscoding.server.handler;

import cn.hutool.core.util.StrUtil;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import net.lesscoding.message.GroupChatRequestMessage;
import net.lesscoding.message.GroupChatResponseMessage;
import net.lesscoding.session.Group;
import net.lesscoding.session.GroupSession;
import net.lesscoding.session.SessionFactory;

import java.util.List;

/**
 * @author eleven
 * @date 2024/10/31 16:21
 * @apiNote
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        String groupName = msg.getGroupName();
        String username = msg.getUsername();
        String content = msg.getContent();
        GroupSession groupSession = SessionFactory.groupSession();
        Group group = groupSession.getGroup(groupName);
        if (group != null) {
            List<Channel> membersChannel = groupSession.getMembersChannel(groupName);
            for (Channel channel : membersChannel) {
                channel.writeAndFlush(new GroupChatResponseMessage(groupName, username, content));
            }
            ctx.writeAndFlush(new GroupChatResponseMessage(true, "发送成功"));
        } else {
            ctx.writeAndFlush(new GroupChatResponseMessage(false, StrUtil.format("群聊{}不存在", groupName)));
        }
    }
}
